package com.sky.aspect;

import com.sky.annontation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Before("@annotation(com.sky.annontation.AutoFill)")
    public void before(JoinPoint jp ) throws Exception {

//
//        @AutoFill(opt= OperationType.UPDATE)
//        void update(Category category);

       MethodSignature signature = (MethodSignature) jp.getSignature();

        Method updateMethod = signature.getMethod();

        AutoFill annotation = updateMethod.getAnnotation(AutoFill.class);
             //获得类型
        OperationType opt = annotation.value();

        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        Object[] args = jp.getArgs();

        if (args==null || args.length==0){

            return;
        }

        //获取 参数
        Object are = args[0];


        if (opt==OperationType.INSERT){


            Method setCreateTime = are.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser = are.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method setUpdateTime = are.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = are.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            setUpdateTime.invoke(are,now);
            setCreateUser.invoke(are,now,currentId);
            setUpdateTime.invoke(are,now);
            setUpdateUser.invoke(are,now,currentId);

        }else if (opt==OperationType.UPDATE){
try {

    Method setUpdateTime = are.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
    Method setUpdateUser = are.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

    setUpdateTime.invoke(are,now);
    setUpdateUser.invoke(are,now,currentId);


}catch (Exception e){
    e.printStackTrace();
}

        }


    }
}
























